package com.ccit.integral.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccit.common.client.EmployeeClient;
import com.ccit.common.exception.GymException;
import com.ccit.common.exception.fileUpload.FileEmptyException;
import com.ccit.common.result.Result;
import com.ccit.common.utils.PageUtil;
import com.ccit.common.utils.RedisUtils;
import com.ccit.common.utils.UploadUtil;
import com.ccit.integral.service.IntegralGoodsService;
import com.ccit.model.IntegralGoods;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(tags = "积分商品管理")
@RestController
@RequestMapping("/integralGoods")
public class IntegralGoodsController {

    @Autowired
    private IntegralGoodsService integralGoodsService;

    @Autowired
    private EmployeeClient employeeClient;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UploadUtil uploadUtil;

    final String port = "8088";


    @ApiOperation(value = "分页查询积分商品")
    @GetMapping("/getIntegralGoodsByPage/{current}/{size}")
    public Result getRecord(@PathVariable Integer current,
                            @PathVariable Integer size) {
        String key = "IntegralGoods:" + current + ":" + size;
        boolean hasKey = redisUtils.hasKey(key);
        Page<IntegralGoods> page;

        if (hasKey) {
            page = (Page<IntegralGoods>)redisUtils.get(key);
        } else {
            Page<IntegralGoods> integralGoodsPage = new Page<>(current, size);
            page = integralGoodsService.page(integralGoodsPage);
            redisUtils.set(key, page);
        }
        return Result.ok(page);

    }

    @ApiOperation(value = "查询所有积分商品")
    @GetMapping("/listAll")
    public Result listAll() {
        List<IntegralGoods> list;
        String key = "allIntegralGoods";
        boolean hasKey = redisUtils.hasKey(key);
        if (hasKey) {
            list = (List<IntegralGoods> )redisUtils.get(key);
        } else {
            list = integralGoodsService.list();
            redisUtils.set(key,list);
        }
        return Result.ok(list);
    }

    @ApiOperation(value = "条件查询")
    @PostMapping("/getByDynamic/{current}/{size}")
    public Result getByDynamic(
            @RequestParam(required = false) String integralGoodsName,
            @PathVariable Integer current,
            @PathVariable Integer size) {
        Page page;
        String key = "integralGoodsList"+ ":" +current + ":" + size;
        if (integralGoodsName != null){
            key = "integralGoodsList"+ ":"  + integralGoodsName + ":" +current + ":" + size;
        }
        boolean hasKey = redisUtils.hasKey(key);
        if (hasKey){
            page = (Page<IntegralGoods>)redisUtils.get(key);
        }else {
            QueryWrapper<IntegralGoods> wrapper = new QueryWrapper<IntegralGoods>();

            if (integralGoodsName != null){
                    wrapper.lambda()
                            .like(IntegralGoods::getName, integralGoodsName)
                            .orderByDesc(IntegralGoods::getExchange);
                }else {
                    wrapper.lambda()
                            .orderByDesc(IntegralGoods::getExchange);
                }
            List<IntegralGoods> list = integralGoodsService.list(wrapper);
            System.out.println(new ArrayList<IntegralGoods>(list.subList(1,list.size())));
            page = PageUtil.getPages(current, size, list);
            redisUtils.set(key,page);;
        }
        return Result.ok(page);
    }


    @ApiOperation(value = "保存积分商品")
    @PostMapping("/saveIntegralGoods")
    public Result saveIntegralGoods(@RequestParam MultipartFile file, @RequestPart String integralGoodsStr) {
        if (file == null) {
            throw new FileEmptyException();
        }
        String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
        Map<String, String> map = new HashMap<>();
        map.put("pathPrefix", pathPrefix);
        map.put("src", "integralGoods");
        String fileName = uploadUtil.saveFile(file, map);
        JSONObject object = JSON.parseObject(integralGoodsStr);

        IntegralGoods integralGoods = new IntegralGoods();
        integralGoods.setName(object.getString("name"));
        integralGoods.setStock(object.getInteger("stock"));
        integralGoods.setExchange(object.getInteger("exchange"));

        System.out.println(fileName);
        integralGoods.setImgUrl("http://localhost:" + port + "/integralGoods/img/" + fileName);
        boolean result = integralGoodsService.save(integralGoods);
        if (result) {
            redisUtils.deleteRedisKeys("IntegralGoods");
            redisUtils.deleteRedisKeys("allIntegralGoods");
            redisUtils.deleteRedisKeys("integralGoodsList");
            return Result.ok("添加成功");
        } else
            return Result.fail().message("添加失败了");
    }

    @ApiOperation(value = "修改积分商品")
    @PutMapping("/updateIntegralGoods")
    public Result updateIntegralGoods(@RequestParam(required = false) MultipartFile file, @RequestPart String integralGoodsStr) {
        //批量模糊删除所有包含keys的数据
        JSONObject object = JSON.parseObject(integralGoodsStr);
        IntegralGoods integralGoods = integralGoodsService.getById(object.getLong("id"));

        integralGoods.setName(object.getString("name"));
        integralGoods.setExchange(object.getInteger("exchange"));
        integralGoods.setStock(object.getInteger("stock"));

        if (file != null) {
            String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
            Map<String, String> map = new HashMap<>();
            map.put("pathPrefix", pathPrefix);
            map.put("src", "integralGoods");
            String fileName = uploadUtil.saveFile(file, map);
            integralGoods.setImgUrl("http://localhost:" + port + "/integralGoods/img/" + fileName);

            /*
            int lastIndexOf = equipment.getImgUrl().lastIndexOf("/");

            String img_path = equipment.getImgUrl().substring(lastIndexOf + 1, equipment.getImgUrl().length());
            System.out.println(img_path);

            String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
            Map<String, String> map = new HashMap<>();
            map.put("pathPrefix", pathPrefix);
            map.put("src", "equipment");
            img_path=pathPrefix + "\\src\\main\\resources\\static\\"+ map.get("src") + "\\img\\"+img_path;

            File oldfile = new File(img_path);
            if (oldfile.exists()){
                if (oldfile.delete()){
                    String fileName = uploadUtil.saveFile(file, map);
                    equipment.setImgUrl("http://localhost:" + port + "/equipment/img/" + fileName);
                }else {
                    return Result.fail().message("删除失败");
                }
            }else {
                return Result.fail().message("文件不存在");
            }*/
        }
        boolean flag = integralGoodsService.updateById(integralGoods);
        if (flag) {
            redisUtils.deleteRedisKeys("IntegralGoods");
            redisUtils.deleteRedisKeys("allIntegralGoods");
            redisUtils.deleteRedisKeys("integralGoodsList");
            return Result.ok();
        } else {
            return Result.fail().message("修改失败");
        }
    }

    @ApiOperation(value = "删除积分商品")
    @DeleteMapping("/deleteIntegralGoods/{id}")
    public Result removeEquipment(@PathVariable("id") Integer id) {
        IntegralGoods integralGoods = integralGoodsService.getById(id);
        if (integralGoods == null) {
            throw new GymException(202, "无此积分商品" + id);
        } else {
            int lastIndexOf = integralGoods.getImgUrl().lastIndexOf("/");
            String img_path = integralGoods.getImgUrl().substring(lastIndexOf + 1, integralGoods.getImgUrl().length());
            System.out.println(img_path);

            String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
            Map<String, String> map = new HashMap<>();
            map.put("pathPrefix", pathPrefix);
            map.put("src", "integralGoods");
            img_path = pathPrefix + "\\src\\main\\resources\\static\\" + map.get("src") + "\\img\\" + img_path;
            File file = new File(img_path);

            boolean byId = integralGoodsService.removeById(id);
            if (byId) {
                redisUtils.deleteRedisKeys("IntegralGoods");
                redisUtils.deleteRedisKeys("allIntegralGoods");
                redisUtils.deleteRedisKeys("integralGoodsList");
                if (file.exists()) {
                    if (!file.delete()) {
                        throw new GymException(203, "删除图片失败");
                    }
                }
            } else throw new GymException(203, "删除失败");
        }

        return Result.ok("删除成功");
    }

    @ApiOperation(value = "批量删除器材")
    @DeleteMapping("/batchRemove")
    public Result batchRemoveEquipment(@RequestBody List<Long> idList) {
        //批量模糊删除所有包含keys的数据
        idList.forEach(id -> {
            IntegralGoods integralGoods = integralGoodsService.getById(id);
            if (integralGoods == null) {
                throw new GymException(202, "无此积分商品" + id);
            } else {
                int lastIndexOf = integralGoods.getImgUrl().lastIndexOf("/");
                String img_path = integralGoods.getImgUrl().substring(lastIndexOf + 1, integralGoods.getImgUrl().length());
                System.out.println(img_path);

                String pathPrefix = new ApplicationHome(this.getClass()).getDir().getParentFile().getParentFile().getAbsolutePath();
                Map<String, String> map = new HashMap<>();
                map.put("pathPrefix", pathPrefix);
                map.put("src", "integralGoods");
                img_path = pathPrefix + "\\src\\main\\resources\\static\\" + map.get("src") + "\\img\\" + img_path;
                File file = new File(img_path);

                boolean byId = integralGoodsService.removeById(id);
                if (byId) {
                    redisUtils.deleteRedisKeys("IntegralGoods");
                    redisUtils.deleteRedisKeys("allIntegralGoods");
                    redisUtils.deleteRedisKeys("integralGoodsList");
                    if (file.exists()) {
                        if (!file.delete()) {
                            throw new GymException(203, "删除图片失败");
                        }
                    }
                } else throw new GymException(203, "删除失败");
            }
        });
        return Result.ok("删除成功");
    }

}
